﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using DealKhuyenMaiV2.com.Models;
using System.Net.Mail;
using System.Net;

namespace DealKhuyenMaiV2.com.Models
{
    public partial class DKMDatabaseEntities
    {
        public bool AddEmail(Email email)
        {
            if (!IsEmailRegistered(email.Email1))
            {
                this.AddToEmails(email);
                this.SaveChanges();
                return true;
            }
            return false;
        }
        

        private bool IsEmailRegistered(String email)
        {
            return this.Emails.Any(r => r.Email1 == email);
        }

        public void SendSubscribeEmail()
        {
            var result = from p in this.Emails select p;

            foreach (Email e in result)
            {
                var fromAddress = new MailAddress("0912315.nguyenvancaonguyen@gmail.com", "From Thaitujim");
                const string fromPassword = "thaitujim"; //wtf

                const string subject = "Mail Subject form DKM website";
                const string body = "Mail Body....";

                string toMailAddress = e.Email1;
                string toMailDisplay = "Hihi";

                var toAddress = new MailAddress(toMailAddress, toMailDisplay);

                var smtp = new SmtpClient
                {
                    Host = "smtp.gmail.com",
                    Port = 587,
                    EnableSsl = true,
                    DeliveryMethod = SmtpDeliveryMethod.Network,
                    UseDefaultCredentials = false,
                    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
                };

                using (var message = new MailMessage(fromAddress, toAddress)
                {
                    Subject = subject,
                    Body = body
                }
                )
                {
                    smtp.Send(message);
                }
            }
        }
    }
}